package com.cheetah.seckill.service;

import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.cheetah.seckill.entity.Order;
import com.cheetah.seckill.mapper.OrderMapper;
import com.cheetah.seckill.mapper.SeckillMapper;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

@Service
public class SeckillService {
    @Autowired
    private RedissonClient redisClient;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SeckillMapper seckillMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public R deleteSeckill(long id) {
        SqlRunner.db().delete("delete from t_order where seckill_id={0}", id);
        SqlRunner.db().update("update seckill set number=100 where id={0}", id);
        RAtomicLong bucket = redisClient.getAtomicLong("sec_" + id);
        bucket.set(100);
        return R.ok(1);
    }

    public R startSeckill(Order order) {

        RAtomicLong bucket = redisClient.getAtomicLong("sec_" + order.getSeckillId());
        if (bucket != null) {
            if (bucket.decrementAndGet()<0) {
                return R.ok("秒杀失败");
            } else {
                order.setState((short) 1);
                order.setCreateTime(new Timestamp(System.currentTimeMillis()));
                this.orderMapper.insert(order);
                this.seckillMapper.updateNum(order.getSeckillId());
                autoCancel(order);
            }
        }

        return R.ok("秒杀成功");
    }

    /**
     *  秒杀成功时，如果用户未及时支付，则10秒钟后自动取消
     */
    void autoCancel(Order order) {
        Message<Order> msg = MessageBuilder.withPayload(order).build();
        this.rocketMQTemplate.asyncSend("order_cancel", msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {

            }

            @Override
            public void onException(Throwable throwable) {
                throwable.printStackTrace();
            }
        }, 3000, 3);
    }

    /**
     * 如果未支付，则取消订单
     * @param order
     * @return
     */
    public R cancel(Order order) {
        Order tmp = this.orderMapper.selectById(order.getId());
        if (5 == tmp.getState()) {
            return R.ok(0);
        }
        this.seckillMapper.cancel(order.getSeckillId());
        order.setState((short) 3);
        this.orderMapper.updateById(order);
        return R.ok(1);
    }

}
